package main

import (
	"fmt"
	"net"
	"strings"
)

import (
	iconv "github.com/djimenez/iconv-go"
	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
)

var le *walk.LineEdit

//var wv *walk.WebView
var outTE *walk.TextEdit
var starBT *walk.PushButton
var stopBT *walk.PushButton

func main() {
	MainWindow{
		Title:   "模拟订单机客户端",
		MinSize: Size{300, 400},
		Size:    Size{500, 600},
		Layout:  VBox{},
		Children: []Widget{
			Composite{
				Layout: Grid{Columns: 3},
				Children: []Widget{
					Label{
						Text: "IMEI号码:",
					},
					LineEdit{
						AssignTo: &le,
						Text:     Bind("IMEI"),
						//width:    20,
						//OnKeyDown: func(key walk.Key) {
						//	if key == walk.KeyReturn {
						//		wv.SetURL(le.Text())
						//	}
						//},
					},
					PushButton{
						Text: "设置",
						OnClicked: func() {
							//addMsg(le.Text())
							if len(le.Text()) == 18 {
								imei = le.Text()
							} else {
								addMsg("imei号码长度错误,请重新输入,imei号码必须为18位数字")
							}

						},
					},
				},
			},
			Composite{
				Layout: Grid{Columns: 2},
				Children: []Widget{
					PushButton{
						AssignTo: &starBT,
						Text:     "启动",
						OnClicked: func() {
							starBT.SetEnabled(false)
							stopBT.SetEnabled(true)
							go star()
						},
					},
					PushButton{
						AssignTo: &stopBT,
						Text:     "停止",
						Enabled:  false,
						OnClicked: func() {
							con.Close()
							addMsg("请求断开连接!")
							starBT.SetEnabled(true)
							stopBT.SetEnabled(false)
						},
					},
				},
			},
			TextEdit{
				AssignTo: &outTE,
				ReadOnly: true,
				Text:     fmt.Sprintf("订单机客模拟户端\n"),
			},
		},
	}.Run()
}

var str, imei string
var msg = make([]byte, 1024)
var (
	//host   = "127.0.0.1"
	host   = "218.241.25.189"
	port   = "6666"
	remote = host + ":" + port
	con    net.Conn
)

func star() {
	var err error
	con, err = net.Dial("tcp", remote)
	if err != nil {
		addMsg("无法连接到服务器.")
		return //这个也可以 可以使程序不强行退出
	}

	addMsg("成功连接服务器!")

	if con == nil {
		addMsg("未连接服务器!")
	}
	if imei == "" {
		imei = "810355839022517280"
	}
	str = "112345678915        " + imei + "               #"
	//发送内容给服务器
	in, err := con.Write([]byte(str))
	if err != nil {
		addMsg("Error when send to server: " + string(in) + "\n")
	}
	//接收服务器的内容
	defer con.Close() //可以接收for循环的错误 然后默认退出连接  这样可以使程序不至于崩溃 要不然会直接退出程序
	for {
		length, err2 := con.Read(msg)
		if err2 != nil {
			addMsg("与服务器断开连接!\n")
			return
		}
		str = string(msg[0:length])
		out, _ := iconv.ConvertString(str, "gb2312", "utf-8")
		outTE.AppendText("From: ")
		//addMsg(str)
		addMsg(out)

		if str == "00" {
			//addMsg("00")
			con.Write([]byte("00"))
		} else {
			sf := strings.Fields(str)
			content := sf[2]
			contents := strings.Split(content, ":")
			id := contents[0][1:]
			word := "112345678920        8151355839022517280               0" + id + "#"
			outTE.AppendText("To: ")
			addMsg(word)
			con.Write([]byte(word))
		}
	}

}

func addMsg(msg string) {
	m := msg + "\n"
	outTE.AppendText(m)
}
